<?php

namespace app\api\controller;

use app\api\model\Goods as GoodsModel;
use app\api\model\Cart as CartModel;
use app\common\service\qrcode\Goods as GoodsPoster;
use app\common\service\qrcode\Poster;
/**
 * 商品控制器
 * Class Goods
 * @package app\api\controller
 */
class Goods extends Controller
{
    // 就诊时段获取
    // public function getVisitTimeSlots($slot, $day)
    // {
    //     $timeSlots = [
    //         '上午' => [],
    //         '下午' => [],
    //         '夜间' => [],
    //     ];
    
    //     // 上午：08:00 ~ 12:00，每30分钟
    //     $morningStart = new \DateTime('08:00');
    //     $morningEnd = new \DateTime('12:00');
    //     while ($morningStart < $morningEnd) {
    //         $endSlot = clone $morningStart;
    //         $endSlot->modify('+30 minutes');
    //         $timeSlots['上午'][] = $morningStart->format('H:i') . '-' . $endSlot->format('H:i');
    //         $morningStart->modify('+30 minutes');
    //     }
    
    //     // 下午：13:00 ~ 17:00，每30分钟
    //     $afternoonStart = new \DateTime('13:00');
    //     $afternoonEnd = new \DateTime('17:00');
    //     while ($afternoonStart < $afternoonEnd) {
    //         $endSlot = clone $afternoonStart;
    //         $endSlot->modify('+30 minutes');
    //         $timeSlots['下午'][] = $afternoonStart->format('H:i') . '-' . $endSlot->format('H:i');
    //         $afternoonStart->modify('+30 minutes');
    //     }
    
    //     // 夜间：18:00 ~ 22:00，每30分钟
    //     $nightStart = new \DateTime('17:00');
    //     $nightEnd = new \DateTime('20:00');
    //     while ($nightStart < $nightEnd) {
    //         $endSlot = clone $nightStart;
    //         $endSlot->modify('+30 minutes');
    //         $timeSlots['夜间'][] = $nightStart->format('H:i') . '-' . $endSlot->format('H:i');
    //         $nightStart->modify('+30 minutes');
    //     }
    
    //     // 当前时间 +30 分钟，只能预约未来半小时之后
    //     $requestedDay = new \DateTime($day);
    //     $currentDate = new \DateTime();
    //     $currentTime = (clone $currentDate)->modify('+30 minutes');
    
    //     // 检查 slot 合法性
    //     if (!isset($timeSlots[$slot])) {
    //         return $this->renderError('无效的时段');
    //     }
    
    //     // 获取可用的时间段（当前日期时判断时间过滤）
    //     $availableSlots = [];
    //     foreach ($timeSlots[$slot] as $timeSlot) {
    //         list($start, $end) = explode('-', $timeSlot);
    //         $slotTime = \DateTime::createFromFormat('H:i', $start);
    
    //         if ($requestedDay->format('Y-m-d') === $currentDate->format('Y-m-d')) {
    //             // 当天则判断是否大于当前时间
    //             if ($slotTime > $currentTime) {
    //                 $availableSlots[] = $timeSlot;
    //             }
    //         } else {
    //             // 非当天所有时段都可用
    //             $availableSlots[] = $timeSlot;
    //         }
    //     }
    
    //     if (empty($availableSlots)) {
    //         return $this->renderError("没有可用时段，当前时间: " . $currentTime->format('H:i'));
    //     }
    
    //     return $this->renderSuccess(compact('availableSlots'));
    // }
    public function getVisitTimeSlots($slot, $day)
    {
        // —— 测试时间：?__now=2025-08-26 16:20:00 ——
        $tz     = new \DateTimeZone('Asia/Shanghai');
        $nowArg = request()->get('__now', '');
        // $nowArg = '2025-09-02 19:30:00';
        $now    = $nowArg ? new \DateTime($nowArg, $tz) : new \DateTime('now', $tz);

        // 定义三段半小时切片
        $timeSlots = [
            '上午' => [],
            '下午' => [],
            '夜间' => [],
        ];

        // 上午：08:00 ~ 12:00
        $morningStart = new \DateTime('08:00', $tz);
        $morningEnd   = new \DateTime('12:00', $tz);
        while ($morningStart < $morningEnd) {
            $endSlot = clone $morningStart;
            $endSlot->modify('+30 minutes');
            $timeSlots['上午'][] = $morningStart->format('H:i') . '-' . $endSlot->format('H:i');
            $morningStart->modify('+30 minutes');
        }

        // 下午：13:00 ~ 17:00
        $afternoonStart = new \DateTime('13:00', $tz);
        $afternoonEnd   = new \DateTime('17:00', $tz);
        while ($afternoonStart < $afternoonEnd) {
            $endSlot = clone $afternoonStart;
            $endSlot->modify('+30 minutes');
            $timeSlots['下午'][] = $afternoonStart->format('H:i') . '-' . $endSlot->format('H:i');
            $afternoonStart->modify('+30 minutes');
        }

        // 夜间：17:00 ~ 20:00
        $nightStart = new \DateTime('17:00', $tz);
        $nightEnd   = new \DateTime('20:00', $tz);
        while ($nightStart < $nightEnd) {
            $endSlot = clone $nightStart;
            $endSlot->modify('+30 minutes');
            $timeSlots['夜间'][] = $nightStart->format('H:i') . '-' . $endSlot->format('H:i');
            $nightStart->modify('+30 minutes');
        }

        // 合法性
        if (!isset($timeSlots[$slot])) {
            return $this->renderError('无效的时段');
        }

        // 截止时间点
        $cutMorning   = new \DateTime('12:00', $tz);
        $cutAfternoon = new \DateTime('17:00', $tz);
        $cutNight     = new \DateTime('19:30', $tz);
        $cutHideToday = new \DateTime('20:00', $tz); // 20:00 后当日不可预约

        $requestedDay = new \DateTime($day, $tz);           // 预约的那天
        $isToday      = ($requestedDay->format('Y-m-d') === $now->format('Y-m-d'));

        // 当日 20:00 后，整天不可预约
        if ($isToday && $now >= $cutHideToday) {
            return $this->renderError('今日预约已截止');
        }

        

        // 获取可用时间段
        $availableSlots = [];
        foreach ($timeSlots[$slot] as $timeSlot) {
            list($start, $end) = explode('-', $timeSlot);

            if ($isToday) {
                // 当天：先看是否过了该时段的截止（严格大于，等于时仍可挂最后一段）
                $deadlinePassed = false;
                if ($slot === '上午' && $now > $cutMorning)     $deadlinePassed = true;
                if ($slot === '下午' && $now > $cutAfternoon)   $deadlinePassed = true;
                if ($slot === '夜间' && $now > $cutNight)       $deadlinePassed = true;
                if ($deadlinePassed) continue;

                // 用“结束时间 ≥ 当前时间”判断是否还能挂
                $slotEnd = \DateTime::createFromFormat('H:i', $end, $tz);
                if ($slotEnd >= $now) {
                    $availableSlots[] = $timeSlot;
                }
            } else {
                // 非当天：整段可用
                $availableSlots[] = $timeSlot;
            }
        }


        if (empty($availableSlots)) {
            return $this->renderError('没有可用时段');
        }

        return $this->renderSuccess(compact('availableSlots'));
    }
    // 按日期预约
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    // public function datereservation()
    // {
    //     $category_id = input('category_id');
    //     $domain = request()->domain();
    //     $currentTime = new \DateTime();
    //     $currentDay = $currentTime->format('Y-m-d');
    //     $endOfNextWeek = (new \DateTime())->modify('+9 days')->format('Y-m-d');
    //     $halfHourLater = (new \DateTime())->modify('+30 minutes');

    //     // 查询未来9天内的所有日期及星期
    //     $days = [];
    //     $dateIterator = new \DateTime();
    //     $weekdays = [
    //         'Sunday' => '周天', 'Monday' => '周一', 'Tuesday' => '周二', 'Wednesday' => '周三',
    //         'Thursday' => '周四', 'Friday' => '周五', 'Saturday' => '周六',
    //     ];
    //     $dateList = [];

    //     for ($i = 0; $i < 8; $i++) {
    //         $date = $dateIterator->format('Y-m-d');
    //         $weekday = $dateIterator->format('w'); // 0=周日，转为 7
    //         $week_day = $weekday == 0 ? 7 : $weekday;
    //         $dateList[] = ['date' => $date, 'week_day' => $week_day, 'dayOfWeek' => $weekdays[$dateIterator->format('l')]];
    //         $dateIterator->modify('+1 day');
    //     }

    //     // 查出某分类下的医生
    //     $goodsIds = Db('goods')
    //         ->where('category_id', $category_id)
    //         ->column('goods_id');

    //     if (empty($goodsIds)) {
    //         return $this->renderSuccess(['days' => []]);
    //     }

    //     // 查询排班数据
    //     $scheduleData = Db('goods_weekly_schedule')
    //         ->whereIn('goods_id', $goodsIds)
    //         ->whereIn('week_day', array_column($dateList, 'week_day'))
    //         ->select();

    //     // 医生详细信息 + 图片等
    //     $goodsInfo = Db('goods')
    //         ->alias('g')
    //         ->join('goods_sku gs', 'g.goods_id = gs.goods_id')
    //         ->join('goods_image gi', 'g.goods_id = gi.goods_id')
    //         ->join('upload_file uf', 'gi.image_id = uf.file_id')
    //         ->whereIn('g.goods_id', $goodsIds)
    //         ->field([
    //             'g.goods_id', 'g.goods_name', 'g.mz_type', 'g.content as con',
    //             'g.selling_point', 'g.sales_initial', 'g.sales_actual',
    //             '(g.sales_initial + g.sales_actual) as goods_sales',
    //             'gs.goods_no', 'gs.goods_sku_id', 'gs.goods_price as price',
    //             'uf.file_name'
    //         ])
    //         ->select();
    //     $goodsMap = [];
    //     foreach ($goodsInfo as $g) {
    //         $g['image_url'] = $domain . '/uploads/' . $g['file_name'];
    //         // 去掉 selling_point 中的 HTML 标签
    //         if (isset($g['selling_point'])) {
    //             $g['selling_point'] = strip_tags(html_entity_decode($g['selling_point']));
    //         }
    //         $goodsMap[$g['goods_id']] = $g;
    //     }

    //     $finalSchedule = [];

    //     foreach ($dateList as $item) {
    //         $date = $item['date'];
    //         $week_day = $item['week_day'];
    //         $dayOfWeek = $item['dayOfWeek'];

    //         $schedule = ['morning' => [], 'afternoon' => [], 'night' => []];

    //         foreach ($scheduleData as $s) {
    //             if ($s['week_day'] != $week_day || !isset($goodsMap[$s['goods_id']])) continue;

    //             $g = $goodsMap[$s['goods_id']];

    //             // 针对当天时间做过滤
    //             $morningNum = $s['morning'] == 1 ? $s['morning_num'] : 0;
    //             $afternoonNum = $s['afternoon'] == 1 ? $s['afternoon_num'] : 0;
    //             $nightNum = $s['night'] == 1 ? $s['night_num'] : 0;

    //             if ($date == $currentDay) {
    //                 $now = $currentTime;
    //                 if ($now >= new \DateTime('11:50')) $morningNum = 0;
    //                 if ($now >= new \DateTime('17:00')) $afternoonNum = 0;
    //                 if ($now >= $halfHourLater) {
    //                     $morningNum = 0;
    //                     $afternoonNum = 0;
    //                     $nightNum = 0;
    //                 }
    //             }

    //             $baseInfo = [
    //                 'goods_id' => $g['goods_id'],
    //                 'goods_sku_id' => $g['goods_sku_id'],
    //                 'goods_name' => $g['goods_name'],
    //                 'goods_sales' => $g['goods_sales'],
    //                 'mz_type' => $g['mz_type'],
    //                 'con' => $g['con'],
    //                 'category_name' => '', // 可选填
    //                 'content' => '', // 可选填
    //                 'selling_point' => $g['selling_point'],
    //                 'goods_no' => $g['goods_no'],
    //                 'price' => $g['price'],
    //                 'image_url' => $g['image_url'],
    //             ];

    //             if ($morningNum > 0) {
    //                 $schedule['morning'][] = array_merge($baseInfo, ['remaining_num' => $morningNum]);
    //             }
    //             if ($afternoonNum > 0) {
    //                 $schedule['afternoon'][] = array_merge($baseInfo, ['remaining_num' => $afternoonNum]);
    //             }
    //             if ($nightNum > 0) {
    //                 $schedule['night'][] = array_merge($baseInfo, ['remaining_num' => $nightNum]);
    //             }
    //         }

    //         // 是否即将放号
    //         $hasSchedule = !empty($schedule['morning']) || !empty($schedule['afternoon']) || !empty($schedule['night']);
    //         if ($date == $dateList[7]['date']) {
    //             $nextDay6am = (new \DateTime())->modify('+1 day')->setTime(6, 0);
    //             if ((new \DateTime()) < $nextDay6am) {
    //                 $countdown = $nextDay6am->getTimestamp() - time();
    //                 $finalSchedule[] = [
    //                     'date' => $date,
    //                     'dayOfWeek' => $dayOfWeek,
    //                     'has_schedule' => '即将放号',
    //                     'schedule' => [
    //                         'countdown' => $countdown,
    //                         'morning' => [],
    //                         'afternoon' => [],
    //                         'night' => [],
    //                     ]
    //                 ];
    //                 continue;
    //             }
    //         }

    //         $finalSchedule[] = [
    //             'date' => $date,
    //             'dayOfWeek' => $dayOfWeek,
    //             'has_schedule' => $hasSchedule ? '有号' : '无号',
    //             'schedule' => $schedule
    //         ];
    //     }

    //     return $this->renderSuccess(['days' => $finalSchedule]);
    // }
    // public function datereservation()
    // {
    //     $category_id = input('category_id');
    //     $domain      = request()->domain();

    //     /** === 可覆盖当前时间（联调专用） ?__now=2025-08-26 16:20:00 === */
    //     $tz     = new \DateTimeZone('Asia/Shanghai');
    //     $nowArg = request()->get('__now', '');
    //     $now    = $nowArg ? new \DateTime($nowArg, $tz) : new \DateTime('now', $tz);

    //     $currentDay = $now->format('Y-m-d');

    //     // 仅“今天”受以下截止时间限制
    //     $cutMorning   = new \DateTime('12:00', $tz);   // 上午截止
    //     $cutAfternoon = new \DateTime('17:00', $tz);   // 下午截止
    //     $cutNight     = new \DateTime('19:30', $tz);   // 夜间截止

    //     // 未来 8 天（含今天）
    //     $dateIterator = clone $now;
    //     $dateIterator->setTime(0, 0, 0);
    //     $weekdays = [
    //         'Sunday' => '周天', 'Monday' => '周一', 'Tuesday' => '周二', 'Wednesday' => '周三',
    //         'Thursday' => '周四', 'Friday' => '周五', 'Saturday' => '周六',
    //     ];
    //     $dateList = [];
    //     for ($i = 0; $i < 8; $i++) {
    //         $date     = $dateIterator->format('Y-m-d');
    //         $weekday  = (int)$dateIterator->format('w'); // 0=周日
    //         $week_day = $weekday === 0 ? 7 : $weekday;   // 1-7（周一到周日）
    //         $dateList[] = [
    //             'date'      => $date,
    //             'week_day'  => $week_day,
    //             'dayOfWeek' => $weekdays[$dateIterator->format('l')],
    //         ];
    //         $dateIterator->modify('+1 day');
    //     }

    //     // 该分类下医生
    //     $goodsIds = Db('goods')->where('category_id', $category_id)->column('goods_id');
    //     if (empty($goodsIds)) {
    //         return $this->renderSuccess(['days' => []]);
    //     }

    //     // 周排班
    //     $scheduleData = Db('goods_weekly_schedule')
    //         ->whereIn('goods_id', $goodsIds)
    //         ->whereIn('week_day', array_column($dateList, 'week_day'))
    //         ->select();

    //     // 医生信息（可能存在多 sku/多图，简单取一条）
    //     $goodsInfo = Db('goods')
    //         ->alias('g')
    //         ->join('goods_sku gs', 'g.goods_id = gs.goods_id')
    //         ->join('goods_image gi', 'g.goods_id = gi.goods_id')
    //         ->join('upload_file uf', 'gi.image_id = uf.file_id')
    //         ->whereIn('g.goods_id', $goodsIds)
    //         ->field([
    //             'g.goods_id', 'g.goods_name', 'g.mz_type', 'g.content as con',
    //             'g.selling_point', 'g.sales_initial', 'g.sales_actual',
    //             '(g.sales_initial + g.sales_actual) as goods_sales',
    //             'gs.goods_no', 'gs.goods_sku_id', 'gs.goods_price as price',
    //             'uf.file_name'
    //         ])
    //         ->select();

    //     $goodsMap = [];
    //     foreach ($goodsInfo as $g) {
    //         // 只保留第一条，避免重复覆盖（如需更精细可再分组）
    //         if (!isset($goodsMap[$g['goods_id']])) {
    //             $g['image_url'] = $domain . '/uploads/' . $g['file_name'];
    //             // 去掉 selling_point 中 HTML
    //             if (isset($g['selling_point'])) {
    //                 $g['selling_point'] = strip_tags(html_entity_decode($g['selling_point']));
    //             }
    //             $goodsMap[$g['goods_id']] = $g;
    //         }
    //     }

    //     $finalSchedule = [];

    //     foreach ($dateList as $item) {
    //         $date      = $item['date'];
    //         $week_day  = $item['week_day'];
    //         $dayOfWeek = $item['dayOfWeek'];

    //         $schedule = ['morning' => [], 'afternoon' => [], 'night' => []];

    //         foreach ($scheduleData as $s) {
    //             if ($s['week_day'] != $week_day || !isset($goodsMap[$s['goods_id']])) continue;

    //             $g = $goodsMap[$s['goods_id']];

    //             // 原始剩余数（只看是否开诊）
    //             $morningNum   = $s['morning']   == 1 ? (int)$s['morning_num']   : 0;
    //             $afternoonNum = $s['afternoon'] == 1 ? (int)$s['afternoon_num'] : 0;
    //             $nightNum     = $s['night']     == 1 ? (int)$s['night_num']     : 0;

    //             // 仅今天受截止时间限制
    //             if ($date === $currentDay) {
    //                 if ($now > $cutMorning)   $morningNum   = 0;
    //                 if ($now > $cutAfternoon) $afternoonNum = 0;
    //                 if ($now > $cutNight)     $nightNum     = 0;
    //             }

    //             $baseInfo = [
    //                 'goods_id'      => $g['goods_id'],
    //                 'goods_sku_id'  => $g['goods_sku_id'],
    //                 'goods_name'    => $g['goods_name'],
    //                 'goods_sales'   => $g['goods_sales'],
    //                 'mz_type'       => $g['mz_type'],
    //                 'con'           => $g['con'],
    //                 'category_name' => '',  // 如需可补充
    //                 'content'       => '',  // 如需可补充
    //                 'selling_point' => $g['selling_point'],
    //                 'goods_no'      => $g['goods_no'],
    //                 'price'         => $g['price'],
    //                 'image_url'     => $g['image_url'],
    //             ];

    //             if ($morningNum > 0) {
    //                 $schedule['morning'][] = $baseInfo + ['remaining_num' => $morningNum];
    //             }
    //             if ($afternoonNum > 0) {
    //                 $schedule['afternoon'][] = $baseInfo + ['remaining_num' => $afternoonNum];
    //             }
    //             if ($nightNum > 0) {
    //                 $schedule['night'][] = $baseInfo + ['remaining_num' => $nightNum];
    //             }
    //         }

    //         // 是否“即将放号”：第 8 天（下一个自然日）的 06:00 前展示倒计时
    //         $hasSchedule = !empty($schedule['morning']) || !empty($schedule['afternoon']) || !empty($schedule['night']);
    //         $isLastDay   = ($date === $dateList[7]['date']);

    //         if ($isLastDay) {
    //             $nextDay6am = (clone $now);
    //             $nextDay6am->modify('+1 day')->setTime(0, 0, 0);
    //             if ($now < $nextDay6am) {
    //                 $countdown = $nextDay6am->getTimestamp() - $now->getTimestamp();
    //                 $finalSchedule[] = [
    //                     'date'        => $date,
    //                     'dayOfWeek'   => $dayOfWeek,
    //                     'has_schedule'=> '即将放号',
    //                     'schedule'    => [
    //                         'countdown' => $countdown,
    //                         'morning'   => [],
    //                         'afternoon' => [],
    //                         'night'     => [],
    //                     ]
    //                 ];
    //                 continue;
    //             }
    //         }

    //         $finalSchedule[] = [
    //             'date'         => $date,
    //             'dayOfWeek'    => $dayOfWeek,
    //             'has_schedule' => $hasSchedule ? '有号' : '无号',
    //             'schedule'     => $schedule
    //         ];
    //     }

    //     return $this->renderSuccess(['days' => $finalSchedule]);
    // }
    public function datereservation()
    {
        $category_id = input('category_id');
        $domain      = request()->domain();

        /** 覆盖当前时间（联调用） ?__now=2025-08-26 16:20:00 */
        $tz     = new \DateTimeZone('Asia/Shanghai');
        $nowArg = request()->get('__now', '');
        $now    = $nowArg ? new \DateTime($nowArg, $tz) : new \DateTime('now', $tz);

        // 当天各截止点
        $cutMorning   = new \DateTime('12:00', $tz);
        $cutAfternoon = new \DateTime('17:00', $tz);
        $cutNight     = new \DateTime('19:30', $tz);

        // “放号时间”改为今天 20:00
        $release20 = (clone $now);
        $release20->setTime(20, 0, 0);

        // --- 生成未来 8 天日期列表：晚于 20:00 则从明天开始 ---
        $startDate = (clone $now);
        $startDate->setTime(0, 0, 0);
        if ($now >= $release20) {
            // 过了 20:00，不展示今天
            $startDate->modify('+1 day');
        }

        $weekdays = [
            'Sunday' => '周天', 'Monday' => '周一', 'Tuesday' => '周二', 'Wednesday' => '周三',
            'Thursday' => '周四', 'Friday' => '周五', 'Saturday' => '周六',
        ];

        $dateList = [];
        $iter = clone $startDate;
        for ($i = 0; $i < 8; $i++) {
            $date     = $iter->format('Y-m-d');
            $weekday  = (int)$iter->format('w');         // 0=周日
            $week_day = $weekday === 0 ? 7 : $weekday;   // 1..7
            $dateList[] = [
                'date'      => $date,
                'week_day'  => $week_day,
                'dayOfWeek' => $weekdays[$iter->format('l')],
            ];
            $iter->modify('+1 day');
        }

        // 该分类下医生
        $goodsIds = Db('goods')->where("is_delete","0")->where('category_id', $category_id)->column('goods_id');
        if (empty($goodsIds)) {
            return $this->renderSuccess(['days' => []]);
        }

        // 周排班
        $scheduleData = Db('goods_weekly_schedule')
            ->whereIn('goods_id', $goodsIds)
            ->whereIn('week_day', array_column($dateList, 'week_day'))
            ->select();

        // 医生信息（取一条图/sku）
        $goodsInfo = Db('goods')
            ->alias('g')
            ->join('goods_sku gs', 'g.goods_id = gs.goods_id')
            ->join('goods_image gi', 'g.goods_id = gi.goods_id')
            ->join('upload_file uf', 'gi.image_id = uf.file_id')
            ->whereIn('g.goods_id', $goodsIds)
            ->field([
                'g.goods_id', 'g.goods_name', 'g.mz_type', 'g.content as con',
                'g.selling_point', 'g.sales_initial', 'g.sales_actual',
                '(g.sales_initial + g.sales_actual) as goods_sales',
                'gs.goods_no', 'gs.goods_sku_id', 'gs.goods_price as price',
                'uf.file_name'
            ])
            ->select();

        $goodsMap = [];
        foreach ($goodsInfo as $g) {
            if (!isset($goodsMap[$g['goods_id']])) {
                $g['image_url'] = $domain . '/uploads/' . $g['file_name'];
                if (isset($g['selling_point'])) {
                    $g['selling_point'] = strip_tags(html_entity_decode($g['selling_point']));
                }
                $goodsMap[$g['goods_id']] = $g;
            }
        }

        $finalSchedule = [];
        $todayStr = (new \DateTime('now', $tz))->format('Y-m-d'); // 真正“今天”的日期串（不受 startDate 影响）

        // foreach ($dateList as $idx => $item) {
        //     $date      = $item['date'];
        //     $week_day  = $item['week_day'];
        //     $dayOfWeek = $item['dayOfWeek'];

        //     $schedule = ['morning' => [], 'afternoon' => [], 'night' => []];

        //     foreach ($scheduleData as $s) {
        //         if ($s['week_day'] != $week_day || !isset($goodsMap[$s['goods_id']])) continue;

        //         $g = $goodsMap[$s['goods_id']];

        //         // 原始剩余数
        //         $morningNum   = $s['morning']   == 1 ? (int)$s['morning_num']   : 0;
        //         $afternoonNum = $s['afternoon'] == 1 ? (int)$s['afternoon_num'] : 0;
        //         $nightNum     = $s['night']     == 1 ? (int)$s['night_num']     : 0;

        //         // 仅“真正今天”受截止点限制（即使今天不在 dateList 里也不影响判断逻辑）
        //         if ($date === $todayStr) {
        //             if ($now > $cutMorning)   $morningNum   = 0;
        //             if ($now > $cutAfternoon) $afternoonNum = 0;
        //             if ($now > $cutNight)     $nightNum     = 0;
        //         }

        //         $baseInfo = [
        //             'goods_id'      => $g['goods_id'],
        //             'goods_sku_id'  => $g['goods_sku_id'],
        //             'goods_name'    => $g['goods_name'],
        //             'goods_sales'   => $g['goods_sales'],
        //             'mz_type'       => $g['mz_type'],
        //             'con'           => $g['con'],
        //             'category_name' => '',
        //             'content'       => '',
        //             'selling_point' => $g['selling_point'],
        //             'goods_no'      => $g['goods_no'],
        //             'price'         => $g['price'],
        //             'image_url'     => $g['image_url'],
        //         ];

        //         if ($morningNum > 0)   $schedule['morning'][]   = $baseInfo + ['remaining_num' => $morningNum];
        //         if ($afternoonNum > 0) $schedule['afternoon'][] = $baseInfo + ['remaining_num' => $afternoonNum];
        //         if ($nightNum > 0)     $schedule['night'][]     = $baseInfo + ['remaining_num' => $nightNum];
        //     }

        //     $hasSchedule = !empty($schedule['morning']) || !empty($schedule['afternoon']) || !empty($schedule['night']);

        //     // 最后一日：20:00 前显示“即将放号”倒计时（目标是“今天 20:00”）
        //     $isLastDay = ($idx === count($dateList) - 1);
        //     if ($isLastDay && $now < $release20) {
        //         $countdown = $release20->getTimestamp() - $now->getTimestamp();
        //         $finalSchedule[] = [
        //             'date'         => $date,
        //             'dayOfWeek'    => $dayOfWeek,
        //             'has_schedule' => '即将放号',
        //             'schedule'     => [
        //                 'countdown' => $countdown,
        //                 'morning'   => [],
        //                 'afternoon' => [],
        //                 'night'     => [],
        //             ]
        //         ];
        //         continue;
        //     }

        //     $finalSchedule[] = [
        //         'date'         => $date,
        //         'dayOfWeek'    => $dayOfWeek,
        //         'has_schedule' => $hasSchedule ? '有号' : '无号',
        //         'schedule'     => $schedule,
        //     ];
        // }
        // ……上文不变……

        foreach ($dateList as $idx => $item) {
            $date      = $item['date'];
            $week_day  = $item['week_day'];
            $dayOfWeek = $item['dayOfWeek'];

            $schedule = ['morning' => [], 'afternoon' => [], 'night' => []];
            $hasSlotGt0 = false; // 是否存在任一时段剩余 > 0

            foreach ($scheduleData as $s) {
                if ($s['week_day'] != $week_day || !isset($goodsMap[$s['goods_id']])) continue;

                $g = $goodsMap[$s['goods_id']];

                // 原始剩余数（开启=1即展示；数量先取表里配置）
                $morningNum   = $s['morning']   == 1 ? (int)$s['morning_num']   : null;
                $afternoonNum = $s['afternoon'] == 1 ? (int)$s['afternoon_num'] : null;
                $nightNum     = $s['night']     == 1 ? (int)$s['night_num']     : null;

                // 仅“真正今天”受截止点限制（过了截点该时段剩余=0；未开启的时段保持 null）
                if ($date === $todayStr) {
                    if ($morningNum   !== null && $now > $cutMorning)   $morningNum   = 0;
                    if ($afternoonNum !== null && $now > $cutAfternoon) $afternoonNum = 0;
                    if ($nightNum     !== null && $now > $cutNight)     $nightNum     = 0;
                }

                $baseInfo = [
                    'goods_id'      => $g['goods_id'],
                    'goods_sku_id'  => $g['goods_sku_id'],
                    'goods_name'    => $g['goods_name'],
                    'goods_sales'   => $g['goods_sales'],
                    'mz_type'       => $g['mz_type'],
                    'con'           => $g['con'],
                    'category_name' => '',
                    'content'       => '',
                    'selling_point' => $g['selling_point'],
                    'goods_no'      => $g['goods_no'],
                    'price'         => $g['price'],
                    'image_url'     => $g['image_url'],
                ];

                // 开启=1 就加入对应时段；remaining_num 可为 0
                if ($morningNum !== null) {
                    if ($morningNum > 0) $hasSlotGt0 = true;
                    $schedule['morning'][] = $baseInfo + ['remaining_num' => $morningNum];
                }
                if ($afternoonNum !== null) {
                    if ($afternoonNum > 0) $hasSlotGt0 = true;
                    $schedule['afternoon'][] = $baseInfo + ['remaining_num' => $afternoonNum];
                }
                if ($nightNum !== null) {
                    if ($nightNum > 0) $hasSlotGt0 = true;
                    $schedule['night'][] = $baseInfo + ['remaining_num' => $nightNum];
                }
            }

            // 最后一日：20:00 前显示“即将放号”
            $isLastDay = ($idx === count($dateList) - 1);
            if ($isLastDay && $now < $release20) {
                $countdown = $release20->getTimestamp() - $now->getTimestamp();
                $finalSchedule[] = [
                    'date'         => $date,
                    'dayOfWeek'    => $dayOfWeek,
                    'has_schedule' => '即将放号',
                    'schedule'     => [
                        'countdown' => $countdown,
                        'morning'   => [],
                        'afternoon' => [],
                        'night'     => [],
                    ]
                ];
                continue;
            }

            // 标记：仅当存在任一 >0 才算“有号”
            $finalSchedule[] = [
                'date'         => $date,
                'dayOfWeek'    => $dayOfWeek,
                'has_schedule' => $hasSlotGt0 ? '有号' : '无号',
                'schedule'     => $schedule,
            ];
        }

        // ……下文不变……
        return $this->renderSuccess(['days' => $finalSchedule]);
    }
    /**
     * 商品列表
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        // 整理请求的参数
        $param = array_merge($this->request->param(), [
            'status' => 10
        ]);
        // 如果没有传 category_id，就设置默认值 10020
        if (empty($param['category_id'])) {
            $param['category_id'] = 10020;
        }
        // 获取列表数据
        $model = new GoodsModel;
        $list = $model->getList($param, $this->getUser(false));
        foreach ($list as $key => $value) {
            if (empty($value['paiban'])) {
                $list->offsetUnset($key);
                continue;
            }
            $list[$key]['mz_type'] = $list[$key]['mz_type']."门诊";
            // 去除 selling_point 字段中的 HTML 标签
            if (isset($value['selling_point'])) {
                $list[$key]['selling_point'] = strip_tags(html_entity_decode($value['selling_point']));
            }
        }
        return $this->renderSuccess(compact('list'));
    }
    public function listss()
    {
        // 整理请求的参数
        $param = array_merge($this->request->param(), [
            'listRows' => 1000000,
        ]);
        // 获取列表数据
        $model = new GoodsModel;
        $list = $model->getList($param, $this->getUser(false));
        return $this->renderSuccess(compact('list'));
    }
    /**
     * 获取商品详情
     * @param $goods_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($goods_id)
    {
        // 用户信息
        $user = $this->getUser(false);
        // 商品详情
        $model = new GoodsModel;
        $goods = $model->getDetails($goods_id, $this->getUser(false));
        $goods['selling_point'] = html_entity_decode($goods['selling_point']);
        if ($goods === false) {
            return $this->renderError($model->getError() ?: '商品信息不存在');
        }
        $goods['selling_point_a'] = strip_tags(html_entity_decode($goods['selling_point']));
        $Qrcode = new Poster($user);
        $ewm = $Qrcode->getImage1($goods_id);
        
        // $qrcode = $this->getImage1($wxappId, 'uid:' . $this->dealer['user_id']);
        // 查询是否关注
        $guanzhu = DB("user_guanzhu")->where("user_id",$user['user_id'])->where("goods_id",$goods_id)->find();
        $guanzhu_num = DB("user_guanzhu")->where("goods_id",$goods_id)->count();
        return $this->renderSuccess([
            // 商品详情
            'detail' => $goods,
            'guanzhu' => $guanzhu,
            'ewm' => $ewm,
            'guanzhu_num' => $guanzhu_num,
            'paiban' => $this->getDoctorSchedule($goods_id),
            // 购物车商品总数量
            'cart_total_num' => $user ? (new CartModel($user))->getTotalNum() : 0,
        ]);
    }
    // public function getDoctorSchedule($doctorId)
    // {
    //     $today = date('Y-m-d');
    //     $currentHour = date('H'); // 获取当前小时
    //     $endDate = date('Y-m-d', strtotime('+8 days'));

    //     // 查询未来8天内该医生的排班情况，并去重
    //     $paibanData = DB('goods_paiban')
    //         ->where('goods_id', '=', $doctorId)
    //         ->whereBetween('day', [$today, $endDate])
    //         ->field('day, morning_num, afternoon_num') // 选择所需字段
    //         ->group('day, morning_num, afternoon_num') // 按字段分组，去除重复数据
    //         ->order('day', 'asc') // 按日期排序
    //         ->select();

    //     // 初始化排班数据
    //     $schedule = [];

    //     // 周几映射表
    //     $weekdays = [
    //         'Sunday' => '周日',
    //         'Monday' => '周一',
    //         'Tuesday' => '周二',
    //         'Wednesday' => '周三',
    //         'Thursday' => '周四',
    //         'Friday' => '周五',
    //         'Saturday' => '周六',
    //     ];

    //     // 遍历排班数据，将上午和下午的数据分别统计
    //     foreach ($paibanData as $paiban) {
    //         $day = $paiban['day'];
    //         $dayOfWeek = $weekdays[date('l', strtotime($day))]; // 获取周几

    //         // 如果是今天，过滤上午和下午的时间段
    //         if ($day == $today) {
    //             // 如果当前时间已过上午11:00，则不显示上午的排班
    //             if ($currentHour < '11:50' && $paiban['morning_num'] > 0) {
    //                 $schedule[] = [
    //                     'day' => $day,
    //                     'dayOfWeek' => $dayOfWeek,
    //                     'time' => '上午',
    //                     'remaining_num' => $paiban['morning_num'],
    //                 ];
    //             }
    //             // 如果当前时间已过下午16:00，则不显示下午的排班
    //             if ($currentHour < '17:00' && $paiban['afternoon_num'] > 0) {
    //                 $schedule[] = [
    //                     'day' => $day,
    //                     'dayOfWeek' => $dayOfWeek,
    //                     'time' => '下午',
    //                     'remaining_num' => $paiban['afternoon_num'],
    //                 ];
    //             }
    //         } else {
    //             // 不是今天则默认添加上午和下午的排班
    //             if ($paiban['morning_num'] > 0) {
    //                 $schedule[] = [
    //                     'day' => $day,
    //                     'dayOfWeek' => $dayOfWeek,
    //                     'time' => '上午',
    //                     'remaining_num' => $paiban['morning_num'],
    //                 ];
    //             }
    //             if ($paiban['afternoon_num'] > 0) {
    //                 $schedule[] = [
    //                     'day' => $day,
    //                     'dayOfWeek' => $dayOfWeek,
    //                     'time' => '下午',
    //                     'remaining_num' => $paiban['afternoon_num'],
    //                 ];
    //             }
    //         }
    //     }

    //     // 返回包含医生ID、排班数据和周几的信息
    //     return [
    //         'goods_id' => $doctorId,
    //         'schedule' => $schedule,
    //     ];
    // }
    // public function getDoctorSchedule($doctorId)
    // {
    //     $today = date('Y-m-d');
    //     $currentTime = date('H:i');
    //     $endDate = date('Y-m-d', strtotime('+8 days'));

    //     // 获取未来8天的日期与周几映射
    //     $scheduleDates = [];
    //     for ($i = 0; $i <= 6; $i++) {
    //         $date = date('Y-m-d', strtotime("+$i day"));
    //         $weekDay = date('N', strtotime($date)); // 周几：1~7
    //         $scheduleDates[$date] = $weekDay;
    //     }

    //     // 查询该医生的每周排班（goods_weekly_schedule）
    //     $weeklySchedule = DB('goods_weekly_schedule')
    //         ->where('goods_id', '=', $doctorId)
    //         ->field('week_day, morning, afternoon, night, morning_num, afternoon_num, night_num')
    //         ->select();

    //     // 将排班数据按 week_day 映射
    //     $groupedSchedule = [];
    //     foreach ($weeklySchedule as $item) {
    //         $groupedSchedule[$item['week_day']] = $item;
    //     }

    //     // 周几映射
    //     $weekdays = [
    //         '1' => '周一',
    //         '2' => '周二',
    //         '3' => '周三',
    //         '4' => '周四',
    //         '5' => '周五',
    //         '6' => '周六',
    //         '7' => '周日',
    //     ];

    //     $schedule = [];

    //     foreach ($scheduleDates as $date => $weekDay) {
    //         $dayOfWeekCn = $weekdays[$weekDay];

    //         if (isset($groupedSchedule[$weekDay])) {
    //             $sch = $groupedSchedule[$weekDay];

    //             // 上午：截止时间 11:50
    //             $morningAvailable = ($sch['morning'] == 1 && $sch['morning_num'] > 0);
    //             if ($date === $today && $currentTime > '11:50') {
    //                 $morningAvailable = false;
    //             }
    //             if ($morningAvailable) {
    //                 $schedule[] = [
    //                     'day' => $date,
    //                     'dayOfWeek' => $dayOfWeekCn,
    //                     'time' => '上午',
    //                     'remaining_num' => $sch['morning_num'],
    //                 ];
    //             }

    //             // 下午：截止时间 17:00
    //             $afternoonAvailable = ($sch['afternoon'] == 1 && $sch['afternoon_num'] > 0);
    //             if ($date === $today && $currentTime > '17:00') {
    //                 $afternoonAvailable = false;
    //             }
    //             if ($afternoonAvailable) {
    //                 $schedule[] = [
    //                     'day' => $date,
    //                     'dayOfWeek' => $dayOfWeekCn,
    //                     'time' => '下午',
    //                     'remaining_num' => $sch['afternoon_num'],
    //                 ];
    //             }

    //             // 夜间：截止时间 22:00
    //             $nightAvailable = ($sch['night'] == 1 && $sch['night_num'] > 0);
    //             if ($date === $today && $currentTime > '22:00') {
    //                 $nightAvailable = false;
    //             }
    //             if ($nightAvailable) {
    //                 $schedule[] = [
    //                     'day' => $date,
    //                     'dayOfWeek' => $dayOfWeekCn,
    //                     'time' => '夜间',
    //                     'remaining_num' => $sch['night_num'],
    //                 ];
    //             }
    //         }
    //     }

    //     return [
    //         'goods_id' => $doctorId,
    //         'schedule' => $schedule,
    //     ];
    // }
    // 升级预约满之前的代码
    // public function getDoctorSchedule($doctorId)
    // {
    //     // —— 测试时间覆盖：?__now=2025-08-26 16:20:00 ——
    //     $tz     = new \DateTimeZone('Asia/Shanghai');
    //     // $nowArg = '2025-09-02 19:30:00';
    //     $nowArg = request()->get('__now', '');
    //     $now    = $nowArg ? new \DateTime($nowArg, $tz) : new \DateTime('now', $tz);

    //     // 截止点
    //     $cutMorning   = new \DateTime('12:00', $tz);  // 上午截止 12:00
    //     $cutAfternoon = new \DateTime('17:00', $tz);  // 下午截止 17:00
    //     $cutNight     = new \DateTime('19:30', $tz);  // 夜间截止 19:30
    //     $cutHideToday = new \DateTime('20:00', $tz);  // 20:00 之后不展示当天

    //     // 生成未来 8 天：20:00 之后跳过今天
    //     $start = (clone $now);
    //     $start->setTime(0, 0, 0);
    //     if ($now >= $cutHideToday) {
    //         $start->modify('+1 day');
    //     }

    //     // 日期 -> 周几(1..7) 列表
    //     $dateList = [];
    //     $iter = clone $start;
    //     for ($i = 0; $i < 8; $i++) {
    //         $date     = $iter->format('Y-m-d');
    //         $weekDay  = (int)$iter->format('N'); // 1..7
    //         $dateList[$date] = $weekDay;
    //         $iter->modify('+1 day');
    //     }

    //     // 取医生周排班
    //     $weekly = DB('goods_weekly_schedule')
    //         ->where('goods_id', '=', $doctorId)
    //         ->field('week_day, morning, afternoon, night, morning_num, afternoon_num, night_num')
    //         ->select();

    //     // week_day => row
    //     $byWeek = [];
    //     foreach ($weekly as $row) {
    //         $byWeek[(int)$row['week_day']] = $row;
    //     }

    //     // 周几映射
    //     $weeknames = ['1'=>'周一','2'=>'周二','3'=>'周三','4'=>'周四','5'=>'周五','6'=>'周六','7'=>'周日'];

    //     $schedule = [];
    //     $todayStr = (new \DateTime('now', $tz))->format('Y-m-d'); // 真·今天（不随 start 改变）

    //     foreach ($dateList as $date => $weekDay) {
    //         if (!isset($byWeek[$weekDay])) continue;
    //         $sch = $byWeek[$weekDay];
    //         $dayName = $weeknames[(string)$weekDay];

    //         // 原始剩余
    //         $mNum = $sch['morning']   == 1 ? (int)$sch['morning_num']   : 0;
    //         $aNum = $sch['afternoon'] == 1 ? (int)$sch['afternoon_num'] : 0;
    //         $nNum = $sch['night']     == 1 ? (int)$sch['night_num']     : 0;

    //         // 仅“今天”受截止限制
    //         if ($date === $todayStr) {
    //             if ($now > $cutMorning)   $mNum = 0;
    //             if ($now > $cutAfternoon) $aNum = 0;
    //             if ($now > $cutNight)     $nNum = 0;
    //         }

    //         if ($mNum > 0) {
    //             $schedule[] = [
    //                 'day'           => $date,
    //                 'dayOfWeek'     => $dayName,
    //                 'time'          => '上午',
    //                 'remaining_num' => $mNum,
    //             ];
    //         }
    //         if ($aNum > 0) {
    //             $schedule[] = [
    //                 'day'           => $date,
    //                 'dayOfWeek'     => $dayName,
    //                 'time'          => '下午',
    //                 'remaining_num' => $aNum,
    //             ];
    //         }
    //         if ($nNum > 0) {
    //             $schedule[] = [
    //                 'day'           => $date,
    //                 'dayOfWeek'     => $dayName,
    //                 'time'          => '夜间',
    //                 'remaining_num' => $nNum,
    //             ];
    //         }
    //     }

    //     return [
    //         'goods_id' => $doctorId,
    //         'schedule' => $schedule,
    //     ];
    // }
    public function getDoctorSchedule($doctorId)
    {
        $tz     = new \DateTimeZone('Asia/Shanghai');
        $nowArg = request()->get('__now', '');
        $now    = $nowArg ? new \DateTime($nowArg, $tz) : new \DateTime('now', $tz);

        // 截止点
        $cutMorning   = new \DateTime('12:00', $tz);  // 上午截止 12:00
        $cutAfternoon = new \DateTime('17:00', $tz);  // 下午截止 17:00
        $cutNight     = new \DateTime('19:30', $tz);  // 夜间截止 19:30
        $cutHideToday = new \DateTime('20:00', $tz);  // 20:00 后不展示当天

        // 未来 8 天，20:00 后从明天开始
        $start = (clone $now);
        $start->setTime(0, 0, 0);
        if ($now >= $cutHideToday) {
            $start->modify('+1 day');
        }

        $dateList = [];
        $iter = clone $start;
        for ($i = 0; $i < 7; $i++) {
            $date    = $iter->format('Y-m-d');
            $weekDay = (int)$iter->format('N'); // 1..7
            $dateList[$date] = $weekDay;
            $iter->modify('+1 day');
        }

        // 周排班
        $weekly = DB('goods_weekly_schedule')
            ->where('goods_id', '=', $doctorId)
            ->field('week_day, morning, afternoon, night, morning_num, afternoon_num, night_num')
            ->select();

        $byWeek = [];
        foreach ($weekly as $row) {
            $byWeek[(int)$row['week_day']] = $row;
        }

        $weeknames = ['1'=>'周一','2'=>'周二','3'=>'周三','4'=>'周四','5'=>'周五','6'=>'周六','7'=>'周日'];
        $schedule  = [];
        $todayStr  = (new \DateTime('now', $tz))->format('Y-m-d'); // 真·今天

        foreach ($dateList as $date => $weekDay) {
            if (!isset($byWeek[$weekDay])) continue;
            $sch = $byWeek[$weekDay];
            $dayName = $weeknames[(string)$weekDay];

            // 是否启用该时段；未启用则不返回
            $mEnabled = ($sch['morning']   == 1);
            $aEnabled = ($sch['afternoon'] == 1);
            $nEnabled = ($sch['night']     == 1);

            // 原始剩余（可能为 0）
            $mNum = (int)$sch['morning_num'];
            $aNum = (int)$sch['afternoon_num'];
            $nNum = (int)$sch['night_num'];

            // 仅“今天”受截止限制：过了截点的时段直接不返回；未过就算 0 也返回
            $allowMorning   = $mEnabled && ($date !== $todayStr || $now <= $cutMorning);
            $allowAfternoon = $aEnabled && ($date !== $todayStr || $now <= $cutAfternoon);
            $allowNight     = $nEnabled && ($date !== $todayStr || $now <= $cutNight);

            if ($allowMorning) {
                $schedule[] = [
                    'day'           => $date,
                    'dayOfWeek'     => $dayName,
                    'time'          => '上午',
                    'remaining_num' => max(0, $mNum), // 0 也要展示
                ];
            }
            if ($allowAfternoon) {
                $schedule[] = [
                    'day'           => $date,
                    'dayOfWeek'     => $dayName,
                    'time'          => '下午',
                    'remaining_num' => max(0, $aNum),
                ];
            }
            if ($allowNight) {
                $schedule[] = [
                    'day'           => $date,
                    'dayOfWeek'     => $dayName,
                    'time'          => '夜间',
                    'remaining_num' => max(0, $nNum),
                ];
            }
        }

        return [
            'goods_id' => $doctorId,
            'schedule' => $schedule,
        ];
    }
    /**
     * 生成商品海报
     * @param $goods_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function poster($goods_id)
    {
        // 商品详情
        $detail = GoodsModel::detail($goods_id);
        $Qrcode = new GoodsPoster($detail, $this->getUser(false));
        return $this->renderSuccess([
            'qrcode' => $Qrcode->getImage(),
        ]);
    }
}
